package emas.server;

import java.util.ArrayList;

import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import emas.client.RetrieveDataService;
import emas.server.authentication.AuthenticationManager;
import emas.server.core.LocationManager;
import emas.shared.EMASConstants;
import emas.shared.Location;

public class RetrieveDataServiceImpl extends RemoteServiceServlet implements
		RetrieveDataService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String currentlyAuthenticatedUser = null;

	@Override
	public ArrayList<Location> getLocations() {
		LocationManager.getInstance().updateLocations();
		return LocationManager.getInstance().getLocations();
	}

	@Override
	public void addLocation(Location location) {
		LocationManager.getInstance().addLocation(location);
	}

	@Override
	public void removeLocation(Location location) {
		LocationManager.getInstance().removeLocation(location);
	}

	@Override
	public void updateLocation(Location location) {
		LocationManager.getInstance().updateLocation(location);
	}

	@Override
	public boolean authenticateUser(String username, String password) {
		boolean userAuthenticated = false;
		HttpSession session = getSession();
		String session_username = (String) session
				.getAttribute(EMASConstants.SESSION_USERNAME);
		String session_password = (String) session
				.getAttribute(EMASConstants.SESSION_PASSWORD);

		if (session_username != null && session_password != null) {
			userAuthenticated = AuthenticationManager.isUserAuthenticated(
					session_username, session_password);
			if (userAuthenticated) {
				currentlyAuthenticatedUser = session_username;
			}
		} else if (username != null && password != null) {
			userAuthenticated = AuthenticationManager.isUserAuthenticated(
					username, password);
			if (userAuthenticated) {
				currentlyAuthenticatedUser = username;
				session.setAttribute(EMASConstants.SESSION_USERNAME, username);
				session.setAttribute(EMASConstants.SESSION_PASSWORD, password);
			}
		} else {
			userAuthenticated = false;
		}
		return userAuthenticated;
	}

	public HttpSession getSession() {
		return this.getThreadLocalRequest().getSession();
	}

	@Override
	public String getCurrentlyAuthenticatedUser() {
		return currentlyAuthenticatedUser;
	}
}
